package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.dto.AcceptanceChecklistTemplateCreateDTO;
import com.ruoyi.system.entity.AcceptanceChecklistItemDO;
import com.ruoyi.system.entity.AcceptanceChecklistTemplateDO;
import com.ruoyi.system.mapper.AcceptanceChecklistItemMapper;
import com.ruoyi.system.mapper.AcceptanceChecklistTemplateMapper;
import com.ruoyi.system.service.AcceptanceChecklistTemplateService;
import com.ruoyi.system.vo.AcceptanceChecklistTemplateVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 验收单模板服务实现类
 * 
 * @author ruoyi
 * @since 2024-01-01
 */
@Service
public class AcceptanceChecklistTemplateServiceImpl implements AcceptanceChecklistTemplateService {

    @Resource
    private AcceptanceChecklistTemplateMapper templateMapper;

    @Resource
    private AcceptanceChecklistItemMapper itemMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createTemplate(AcceptanceChecklistTemplateCreateDTO createDTO) {
        // 创建模板
        AcceptanceChecklistTemplateDO template = new AcceptanceChecklistTemplateDO();
        BeanUtils.copyProperties(createDTO, template);
        template.setStatus(1);
        template.setCreateBy(SecurityUtils.getUsername());
        template.setCreateTime(LocalDateTime.now());
        templateMapper.insert(template);

        // 创建模板项
        for (AcceptanceChecklistTemplateCreateDTO.TemplateItemDTO itemDTO : createDTO.getItems()) {
            AcceptanceChecklistItemDO item = new AcceptanceChecklistItemDO();
            BeanUtils.copyProperties(itemDTO, item);
            item.setTemplateId(template.getId());
            item.setCreateBy(SecurityUtils.getUsername());
            item.setCreateTime(LocalDateTime.now());
            itemMapper.insert(item);
        }

        return template.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateTemplate(Long templateId, AcceptanceChecklistTemplateCreateDTO createDTO) {
        // 更新模板
        AcceptanceChecklistTemplateDO template = new AcceptanceChecklistTemplateDO();
        BeanUtils.copyProperties(createDTO, template);
        template.setId(templateId);
        template.setUpdateBy(SecurityUtils.getUsername());
        template.setUpdateTime(LocalDateTime.now());
        templateMapper.updateById(template);

        // 删除原有模板项
        LambdaQueryWrapper<AcceptanceChecklistItemDO> deleteWrapper = new LambdaQueryWrapper<>();
        deleteWrapper.eq(AcceptanceChecklistItemDO::getTemplateId, templateId);
        itemMapper.delete(deleteWrapper);

        // 创建新的模板项
        for (AcceptanceChecklistTemplateCreateDTO.TemplateItemDTO itemDTO : createDTO.getItems()) {
            AcceptanceChecklistItemDO item = new AcceptanceChecklistItemDO();
            BeanUtils.copyProperties(itemDTO, item);
            item.setTemplateId(templateId);
            item.setCreateBy(SecurityUtils.getUsername());
            item.setCreateTime(LocalDateTime.now());
            itemMapper.insert(item);
        }

        return true;
    }

    @Override
    public Boolean deleteTemplate(Long templateId) {
        AcceptanceChecklistTemplateDO template = new AcceptanceChecklistTemplateDO();
        template.setId(templateId);
        template.setIsDeleted(1);
        template.setUpdateBy(SecurityUtils.getUsername());
        template.setUpdateTime(LocalDateTime.now());
        return templateMapper.updateById(template) > 0;
    }

    @Override
    public AcceptanceChecklistTemplateVO getTemplateDetail(Long templateId) {
        // 查询模板
        AcceptanceChecklistTemplateDO template = templateMapper.selectById(templateId);
        if (template == null) {
            return null;
        }

        // 查询模板项
        LambdaQueryWrapper<AcceptanceChecklistItemDO> itemWrapper = new LambdaQueryWrapper<>();
        itemWrapper.eq(AcceptanceChecklistItemDO::getTemplateId, templateId)
                .orderByAsc(AcceptanceChecklistItemDO::getSeqNo);
        List<AcceptanceChecklistItemDO> items = itemMapper.selectList(itemWrapper);

        // 转换为VO
        AcceptanceChecklistTemplateVO vo = new AcceptanceChecklistTemplateVO();
        BeanUtils.copyProperties(template, vo);
        
        List<AcceptanceChecklistTemplateVO.TemplateItemVO> itemVOs = items.stream()
                .map(item -> {
                    AcceptanceChecklistTemplateVO.TemplateItemVO itemVO = new AcceptanceChecklistTemplateVO.TemplateItemVO();
                    BeanUtils.copyProperties(item, itemVO);
                    return itemVO;
                })
                .collect(Collectors.toList());
        vo.setItems(itemVOs);

        return vo;
    }

    @Override
    public Page<AcceptanceChecklistTemplateVO> pageTemplates(Long projectId, Long stageId, String templateName, Integer status, int pageNum, int pageSize) {
        Page<AcceptanceChecklistTemplateDO> page = new Page<>(pageNum, pageSize);
        
        LambdaQueryWrapper<AcceptanceChecklistTemplateDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(projectId != null, AcceptanceChecklistTemplateDO::getProjectId, projectId)
                .eq(stageId != null, AcceptanceChecklistTemplateDO::getStageId, stageId)
                .like(StringUtils.isNotEmpty(templateName), AcceptanceChecklistTemplateDO::getTemplateName, templateName)
                .eq(status != null, AcceptanceChecklistTemplateDO::getStatus, status)
                .orderByDesc(AcceptanceChecklistTemplateDO::getCreateTime);

        Page<AcceptanceChecklistTemplateDO> result = templateMapper.selectPage(page, wrapper);
        
        // 转换为VO
        Page<AcceptanceChecklistTemplateVO> voPage = new Page<>();
        BeanUtils.copyProperties(result, voPage);
        
        List<AcceptanceChecklistTemplateVO> voList = result.getRecords().stream()
                .map(template -> {
                    AcceptanceChecklistTemplateVO vo = new AcceptanceChecklistTemplateVO();
                    BeanUtils.copyProperties(template, vo);
                    return vo;
                })
                .collect(Collectors.toList());
        voPage.setRecords(voList);

        return voPage;
    }

    @Override
    public List<AcceptanceChecklistTemplateVO> getEnabledTemplatesByProjectStage(Long projectId, Long stageId) {
        LambdaQueryWrapper<AcceptanceChecklistTemplateDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AcceptanceChecklistTemplateDO::getProjectId, projectId)
                .eq(AcceptanceChecklistTemplateDO::getStageId, stageId)
                .eq(AcceptanceChecklistTemplateDO::getStatus, 1)
                .orderByDesc(AcceptanceChecklistTemplateDO::getCreateTime);

        List<AcceptanceChecklistTemplateDO> templates = templateMapper.selectList(wrapper);
        
        return templates.stream()
                .map(template -> {
                    AcceptanceChecklistTemplateVO vo = new AcceptanceChecklistTemplateVO();
                    BeanUtils.copyProperties(template, vo);
                    return vo;
                })
                .collect(Collectors.toList());
    }

    @Override
    public Boolean updateTemplateStatus(Long templateId, Integer status) {
        AcceptanceChecklistTemplateDO template = new AcceptanceChecklistTemplateDO();
        template.setId(templateId);
        template.setStatus(status);
        template.setUpdateBy(SecurityUtils.getUsername());
        template.setUpdateTime(LocalDateTime.now());
        return templateMapper.updateById(template) > 0;
    }
}

